import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {partClaimType, partClaimReportCacuStatus, partClaimStatus, currency, partClaimReasonStatus, partClaimResultStatus} from '../Enum';
import routes from './routes';
import {TABLE, DATE_FORMAT, FILES_API} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount, formatPercent} from '../utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {getDetail, abandonData, submitData} from './api';
import {injectIntl} from './intl';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import styles from './style.css';
const {Description} = DescriptionList;
class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        details: res.data.partClaimReportDetail
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onClickSubmitBtn = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        submitData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        abandonData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    render() {
        const {data} = this.state;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickSubmitBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.submit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'detailPanel.submit',
                        defaultMessage: '提交'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(data.options, PERMISSION.confirm))
            operations.push(<Button key="confirm" href={`#${routes.confirm.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.confirm',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件中文名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimAmount',
                defaultMessage: '索赔数量'
            }),
            dataIndex: 'claimAmount'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '索赔单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.fobAmount',
                defaultMessage: 'FOB金额'
            }),
            dataIndex: 'fobAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.mgmtFee',
                defaultMessage: '管理费'
            }),
            dataIndex: 'mgmtFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.totalAmount',
                defaultMessage: '总金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.payAmount',
                defaultMessage: '赔付金额'
            }),
            dataIndex: 'payAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.claimResult',
                defaultMessage: '索赔结果'
            }),
            dataIndex: 'claimResult',
            render: text => conventEnumValueToString(partClaimResultStatus, text)
        }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.partBackOrder',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col>
                        </Row>}>
                            {!this.props.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.branchCode',
                                    defaultMessage: '营销分公司编号'
                                })}>{data.branchCode}
                                </Description>
                            }
                            {!this.props.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.branchName',
                                    defaultMessage: '营销分公司名称'
                                })}>{data.branchName}
                                </Description>
                            }
                            {!this.props.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.brandCode',
                                    defaultMessage: '品牌编号'
                                })}>{data.brandCode}
                                </Description>
                            }
                            {!this.props.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.brandName',
                                    defaultMessage: '品牌名称'
                                })}>{data.brandName}
                                </Description>
                            }
                            {!this.props.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.dealerCode',
                                    defaultMessage: '总代编号'
                                })}>{data.dealerCode}
                                </Description>
                            }
                            {!this.props.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.dealerName',
                                    defaultMessage: '总代名称'
                                })}>{data.dealerName}
                                </Description>
                            }
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.code',
                                defaultMessage: '索赔报告编号'
                            })}>{data.code}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.status',
                                defaultMessage: '状态'
                            })}>{conventEnumValueToString(partClaimStatus, data.status)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.claimCode',
                                defaultMessage: '备件索赔单编号'
                            })}>{data.claimCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.createTime',
                                defaultMessage: '申请日期'
                            })}>{formatDateTime(data.createTime, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.invoiceCode',
                                defaultMessage: '发票号'
                            })}>{data.invoiceCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.invoicedDate',
                                defaultMessage: '开票日期'
                            })}>{formatDateTime(data.invoicedDate, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.claimType',
                                defaultMessage: '索赔类型'
                            })}>{conventEnumValueToString(partClaimType, data.claimType)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receiptDate',
                                defaultMessage: '收货日期'
                            })}>{formatDateTime(data.receiptDate, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.mgmtRate',
                                defaultMessage: '管理费率'
                            })}>{data.isMgmFee ? formatPercent(data.mgmtRate) : 0}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.shipmentDate',
                                defaultMessage: '出运日期'
                            })}>{formatDateTime(data.shipmentDate, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.actualArrivalDate',
                                defaultMessage: '到达日期'
                            })}>{formatDateTime(data.actualArrivalDate, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.destination',
                                defaultMessage: '目的地'
                            })}>{data.destination}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.claimAmount',
                                defaultMessage: '索赔总数量'
                            })}>{data.claimAmount}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.totalFee',
                                defaultMessage: '索赔总金额'
                            })}>{formatAmount(data.totalFee)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.address',
                                defaultMessage: '地址'
                            })}>{data.address}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.contactNumber',
                                defaultMessage: '联系电话'
                            })}>{data.contactNumber}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.surveyResults',
                                defaultMessage: '调查结果'
                            })}>{data.surveyResults}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.preventMeasures',
                                defaultMessage: '预防措施'
                            })}>{data.preventMeasures}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.treatmentScheme',
                                defaultMessage: '处理方案'
                            })}>{conventEnumValueToString(partClaimResultStatus, data.treatmentScheme)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.payType',
                                defaultMessage: '支付方式'
                            })}>{data.payType}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.cacuStatus',
                                defaultMessage: '结算状态'
                            })}>{conventEnumValueToString(partClaimReportCacuStatus, data.cacuStatus)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.createName',
                                defaultMessage: '创建人姓名'
                            })}>{data.createName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.operateTime',
                                defaultMessage: '编辑时间'
                            })}>{formatDateTime(data.operateTime, DATE_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.operateName',
                                defaultMessage: '编辑人姓名'
                            })}>{data.operateName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.confirmorName',
                                defaultMessage: '确认人姓名'
                            })}>{data.confirmorName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.confirmTime',
                                defaultMessage: '确认时间'
                            })}>{formatDateTime(data.confirmTime, DATE_FORMAT)}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: '清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="partId"
                                pagination={false}
                                dataSource={this.state.details}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    { data.attachments && data.attachments.length >= 0
                        ? <Card><DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.card.attachment',
                            defaultMessage: 'PI附件'
                        })}>
                            {data.attachments.map(item => (<Description key={item.fileId}>
                                <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                    {item.fileName}</a></Description>))}
                        </DescriptionList></Card>
                        : <Card><DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.content.noAttachment',
                            defaultMessage: '暂无附件'
                        })}>
                        </DescriptionList></Card>}
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    permissions: PropTypes.array
};

import {connect} from 'react-redux';
import {
    tableSearch,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
